import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";
export default class GameControl {
  food: Food;
  scorePanel: ScorePanel;
  snake: Snake;
  direction: string = "";
  isAlive: boolean = true;
  constructor() {
    console.log("游戏开始了");
    this.food = new Food();
    this.scorePanel = new ScorePanel();
    this.snake = new Snake();
    this.init();
  }
  init() {
    document.addEventListener("keydown", this.keydownHandler.bind(this));
    this.run();
  }
  keydownHandler(e: KeyboardEvent) {
    this.direction = e.key;
  }
  run() {
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch (this.direction) {
      case "ArrowUp":
      case "Up":
        // 向上移动 top 减少
        Y -= 10;
        break;
      case "ArrowDown":
      case "Down":
        // 向下移动 top 增加
        Y += 10;
        break;
      case "ArrowLeft":
      case "Left":
        // 向左移动 left 减少
        X -= 10;
        break;
      case "ArrowRight":
      case "Right":
        // 向右移动 left 增加
        X += 10;
        break;
    }
    this.checkEat(X,Y)
    try {
      this.snake.X = X;
      this.snake.Y = Y;
    } catch (error) {
      alert(error.message);
      this.isAlive = false;
    }
    this.isAlive && setTimeout(this.run.bind(this), 150);
  }
  checkEat(X: number, Y: number): void {
      if(this.food.X===X &&this.food.Y ===Y){
          this.food.change();
          this.scorePanel.addScore();
          this.snake.addBody();
      }
  }
}
